package cc.magicjson.example.demo.tsp.benchmark;

import cc.magicjson.example.demo.concurrent.MergeAndGroupListsBenchmark;
import cc.magicjson.example.demo.tsp.DynamicProgrammingTSP;
import cc.magicjson.example.demo.tsp.GeneticTSP;
import cc.magicjson.example.demo.tsp.GreedyTSP;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime) // 使用平均时间作为基准测试模式
@OutputTimeUnit(TimeUnit.MILLISECONDS) // 输出时间单位为毫秒
@State(Scope.Thread) // 每个线程维护一个实例
public class TSPBenchmark {

	private static final int[][] dist = {
			{0, 10, 15, 20},
			{10, 0, 35, 25},
			{15, 35, 0, 30},
			{20, 25, 30, 0}
	};

	private GreedyTSP greedyTSP;
	private DynamicProgrammingTSP dpTSP;
	private GeneticTSP geneticTSP;

	@Setup(Level.Trial) // 在测试前初始化
	public void setup() {
		greedyTSP = new GreedyTSP(dist);
		dpTSP = new DynamicProgrammingTSP(dist);
		geneticTSP = new GeneticTSP(dist, 100, 0.01, 500);
	}

	@Benchmark
	public int testGreedyTSP() {
		return greedyTSP.findShortestPath();
	}

	@Benchmark
	public int testDynamicProgrammingTSP() {
		return dpTSP.findShortestPath();
	}

	@Benchmark
	public int testGeneticTSP() {
		return geneticTSP.findShortestPath();
	}

	public static void main(String[] args) throws Exception {
//        org.openjdk.jmh.Main.main(args); // 启动JMH基准测试
		Options options = new OptionsBuilder()
				.include(TSPBenchmark.class.getName())
//                .mode(Mode.Throughput)
//                .timeUnit(TimeUnit.MILLISECONDS)
				.warmupIterations(3)
				.forks(1)
				.build();
		new Runner(options).run();
	}
}
